#!/usr/bin/env python
# -*- coding: utf-8 -*-
from string import Template
from tack.lib import json_app, content_headers, status_codes
from datetime import datetime, timedelta
from tack_ocie.api.util import state_def, build_row_dict

ymd_format = '%Y-%m-%d'

get_by_date_range_sql = """
SELECT start, finish, appointment_type_id
FROM ocie_schedule
WHERE CONVERT(CHAR(10),start,121) = '$working_date' 
  AND state_finish IS NULL AND state_key = $resourced_state
ORDER BY start
"""

def get_by_date_range(environ, start_response):
    try:
        start_date = datetime.strptime(environ['dispatcher.groups']['start'],ymd_format)
        finish_date = datetime.strptime(environ['dispatcher.groups']['finish'],ymd_format)
    except:
        start_response(status_codes.error, content_headers.default_plain())
        return ['Error']
    output = {}
    day_range = range(0, (finish_date - start_date).days + 1)
    cursor = environ['connection'].cursor()
    for day_diff in day_range:
        working_date = (start_date + timedelta(days=day_diff)).strftime(ymd_format)
        resourced_state = state_def.RESOURCED
        sql = Template(get_by_date_range_sql).substitute(locals())
        cursor.execute(sql)
        rows = cursor.fetchall()
        event_list = []
        for row in rows:
            row_dict = build_row_dict(cursor.description, row)
            start = row_dict['start'][11:13] + row_dict['start'][14:16]
            finish = row_dict['finish'][11:13] + row_dict['finish'][14:16]
            if not(start >= "1630") and not(finish <= "0730") :
                row_dict['start'] = row_dict['start'] if start >= "0730" else row_dict['start'][0:11] + '07:30:00'
                row_dict['finish'] = row_dict['finish'] if finish <= "1630" else row_dict['finish'][0:11] + '16:30:00'
                row_dict['appointment_type'] = "Booked" if row_dict['appointment_type_id'] != 7 else "Closed"
                event_list.append(row_dict)
        output[working_date] = event_list
    return json_app(output)(environ, start_response)
